package com.wx.hd;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.UUID;

import org.apache.log4j.Logger;

public class ImageDownload {
	private static Logger logger = Logger.getLogger(ImageDownload.class);
    public static void main(String[] args) {
    	demo.filepath = "D://picture//";
        String url = "http://www.gaoimg.com/uploads/allimg/190911/1-1Z911152343V1.jpg";
        long s = Calendar.getInstance().getTimeInMillis();
        downloadPicture(url);
        long e = Calendar.getInstance().getTimeInMillis();
        System.out.println("网络文件下载耗时："+(e-s)+"毫秒");
    }
    //链接url下载图片
    public static void downloadPicture(String urlList) {
        URL url = null;
       
        try {
        	String[] str = urlList.split("/");
            url = new URL(urlList);
            //long s = Calendar.getInstance().getTimeInMillis();
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            //long e = Calendar.getInstance().getTimeInMillis();
            //System.out.println("网络文件数据流创建耗时："+(e-s)+"毫秒");
            //图片保存路径
            //long s1 = Calendar.getInstance().getTimeInMillis();
            String imageName =  demo.filepath+"//"+str[str.length-1];
            //String imageName =  "D://picture//"+UUID.randomUUID()+"."+filetype;
            //long e1 = Calendar.getInstance().getTimeInMillis();
            //System.out.println("使用UUID创建文件名称耗时："+(e1-s1)+"毫秒");
            File file = new File(demo.filepath);
            //自动创建文件目录
            if(!file.exists()){
            	file.mkdirs();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
            logger.debug("=================文件创建成功");
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024*1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            fileOutputStream.flush();
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
        	logger.debug("=================网络地址异常："+e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
        	logger.debug("=================文件下载失败："+e.getMessage());
            e.printStackTrace();
        }
    }
}
